package com.blrs.utils;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

public class SmsHttpApi {

    private static final String MT_URL = "http://222.246.135.226:6790/submitsm";
    private static final String MO_URL = "http://222.246.135.226:6790/rcvsms";

    // 计算MD5加密字符串
    private static String calculateHash(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte b : array) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    // 发送MT消息
    public static String sendMtMessage(String accountName, String password, String destAddr, String sourceAddr, String content, String serviceCode) throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MINUTE, -1);
        // 格式化时间
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
        String hashContent="MD5:" + accountName + ":" + password + ":" + date;
        System.out.println(hashContent);
        String hash = calculateHash(hashContent);
        System.out.println("Hash: " + hash);

        System.out.println("Content: " + content); // 打印 content 的值

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("accountName", accountName);
        Map<String, String> authorization = new HashMap<>();
        authorization.put("Algorithm", "MD5");
        authorization.put("Date", date);
        authorization.put("HASHHEX", hash);
        requestBody.put("Authorization", authorization);
        requestBody.put("DestAddr", destAddr);
        requestBody.put("SourceAddr", sourceAddr);
        requestBody.put("Content", content);
        requestBody.put("ServiceCode", serviceCode);
        String jsonString = JSONObject.toJSONString(requestBody);
        System.out.println("MT Request: " + jsonString);
        return sendHttpPost(MT_URL, jsonString);
    }

    // 查询MO和状态报告
    public static String queryMoAndStatus(String accountName, String password) throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MINUTE, -1);
        // 格式化时间
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
        String hash = calculateHash("MD5:" + accountName + ":" + password + ":" + date);

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("accountName", accountName);
        Map<String, String> authorization = new HashMap<>();
        authorization.put("Algorithm", "MD5");
        authorization.put("Date", date);
        authorization.put("HASHHEX", hash);
        requestBody.put("Authorization", authorization);
        String jsonString = JSONObject.toJSONString(requestBody);

        return sendHttpPost(MO_URL, jsonString);
    }

    // 通用POST请求
// 通用POST请求
    private static String sendHttpPost(String url, String requestBody) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        post.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON)); // 设置编码为 UTF-8
        post.setHeader("Accept-Language","UTF-8");
        post.setHeader("Content-Type", "application/json;charset=utf-8");
        try (CloseableHttpResponse response = httpClient.execute(post)) {
            if (response.getCode() == 200) {
                System.out.println("HTTP Status: " + response.getCode());
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                throw new RuntimeException("HTTP Error: " + response.getCode());
            }
        }
    }

    public static void main(String[] args) {
        try {
            // 示例调用MT消息发送接口
            String mtResponse = sendMtMessage(
                    "30181",
                    "t7CKeT",
                    "13043687265",
                    "1069100010060",
                    "【测试短信内容,签名:【湖南数生调试】",
                    "PUSH"
            );
            System.out.println("MT Response: " + mtResponse);

            // 示例调用MO及状态报告接口
            String moResponse = queryMoAndStatus("693648", "12345");
            System.out.println("MO Response: " + moResponse);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
